package com.meng.system.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.meng.system.domain.vo.ResponseVO;
import com.meng.system.domain.vo.UserInfoVO;
import com.meng.system.enums.ErrorEnum;
import com.meng.system.security.MiniUserDetails;
import com.meng.system.service.auth.SysUserService;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 认证成功返回处理器
 * @author Mr.Still
 * @version 1.0.0
 * @date 2021-06-14 00:35
 **/
@Component
public class MySuccessHandler implements AuthenticationSuccessHandler {

    private final SysUserService sysUserService;

    public MySuccessHandler(SysUserService sysUserService) {
        this.sysUserService = sysUserService;
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        MiniUserDetails user = (MiniUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        UserInfoVO userInfo = sysUserService.getUserInfoByUserId(user);
        String userInfoStr = JSON.toJSONString(ResponseVO.result(ErrorEnum.SUCCESS,userInfo), SerializerFeature.DisableCircularReferenceDetect);
        response.getWriter().write(userInfoStr);
    }
}
